package org.hbhk.hms.mq;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.hbhk.hms.entity.HmsMq;
import org.hbhk.hms.mapper.HmsMqMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Maps;

@Service
@Order(100)
public class MqProvider {

	protected static final Logger logger = LoggerFactory.getLogger(MqProvider.class);

	public static Map<String, DefaultMQProducer> mqProducerCache = Maps.newConcurrentMap();

	@Value("${mq.namesrvAddr}")
	private String namesrvAddr;

	public static final String hmsDelayMq = "hmsDelayMqprovider";

	@Autowired
	private HmsMqMapper hmsMqMapper;

	public static boolean start = false;

	public static DefaultMQProducer get(String mqName) {
		if (!mqProducerCache.containsKey(mqName)) {
			throw new RuntimeException(mqName + " not exist ");
		}
		return mqProducerCache.get(mqName);
	}

	private void buildDefaultMQProducer(String mqName, String serverUrl) throws Exception {
		if (mqProducerCache.containsKey(mqName)) {
			return;
		}
		synchronized (logger) {
			if (!mqProducerCache.containsKey(mqName)) {
				if (StringUtils.isNotEmpty(mqName)) {

					DefaultMQProducer defaultMQProducer = new DefaultMQProducer(mqName);
					defaultMQProducer.setNamesrvAddr(serverUrl);
					defaultMQProducer.start();
					mqProducerCache.put(mqName, defaultMQProducer);

				}

			}
		}
	}

	@PostConstruct
	public void afterPropertiesSet() throws Exception {
		buildDefaultMQProducer(hmsDelayMq, namesrvAddr);
		logger.error("add  mq provider :" + hmsDelayMq + "," + namesrvAddr);
		QueryWrapper<HmsMq> queryWrapper = new QueryWrapper<>();
		queryWrapper.eq("status", 1);
		List<HmsMq> hmsTopicList = hmsMqMapper.selectList(queryWrapper);
		if (hmsTopicList != null) {
			for (HmsMq hmsMq : hmsTopicList) {
				logger.error(" add  mq provider :" + hmsMq.getMqName() + "," + hmsMq.getNamesrvAddr());
				buildDefaultMQProducer(hmsMq.getMqName(), hmsMq.getNamesrvAddr());
			}
		}
		start = true;
	}

}
